package com.qyhl.school.school.vlog.play;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.orhanobut.hawk.Hawk;
import com.qyhl.school.R;
import com.qyhl.school.R2;
import com.qyhl.school.school.vlog.comment.SchoolVlogCommentPopupWindow;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.school.SchoolVlogBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.MShareBoard;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.module_microvideo.shortvideo.play.pagerlayoutmanager.OnViewPagerListener;
import com.qyhl.webtv.module_microvideo.shortvideo.play.pagerlayoutmanager.ViewPagerLayoutManager;
import com.qyhl.webtv.module_microvideo.shortvideo.play.player.ListVideoView;
import com.qyhl.webtv.module_microvideo.shortvideo.play.player.OnItemChildClickListener;
import com.qyhl.webtv.module_microvideo.shortvideo.play.player.VideoManager;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.umeng.socialize.UMShareAPI;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import es.dmoral.toasty.Toasty;
import tv.danmaku.ijk.media.player.IMediaPlayer;

@Route(path = ARouterPathConstant.SCHOOL_VLOG_PLAY)
public class SchoolVlogPlayActivity extends BaseActivity implements OnViewPagerListener, SchoolVlogPlayContract.SchoolVlogPlayView {
    @BindView(R2.id.recycle_view)
    RecyclerView recycleView;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;

    ViewPagerLayoutManager pagerLayoutManager;
    VlogVideoAdapter videoAdapter;

    private List<SchoolVlogBean> mDataList;
    private int curPosition;

    private VlogVideoAdapter.VideoViewHolder viewHolder;

    private String userName;

    private int vlogId;

    private int tagId;

    private boolean isFirst = false;

    private SchoolVlogPlayPresenter mPresenter;

    private int lastId;
    private int lastBoost;

    private int type;

    @Override
    protected int getContentView() {
        return R.layout.activity_school_vlog_play;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        mImmersionBar
                .statusBarDarkFont(false)
                .init();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        curPosition = getIntent().getIntExtra("position", 0);
        mDataList = (List<SchoolVlogBean>) getIntent().getBundleExtra("list").getSerializable("bean");
        tagId = getIntent().getIntExtra("tagId", 0);
        type = getIntent().getIntExtra("type", 0);
        if (mDataList != null) {
            vlogId = mDataList.get(curPosition).getId();
            lastId = mDataList.get(mDataList.size() - 1).getId();
            lastBoost = mDataList.get(mDataList.size() - 1).getBoost();
        } else {
            vlogId = 0;
            lastId = 0;
            lastBoost = 0;
        }

        if (Hawk.contains("login")) {
            userName = CommonUtils.getInstance().getUserName();
        } else {
            userName = "";
        }

        isFirst = true;
        mPresenter = new SchoolVlogPlayPresenter(this);

        refresh.setRefreshFooter(new ClassicsFooter(this));
        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setEnableRefresh(false);

        refresh.setEnableLoadMore(type == 0);

        pagerLayoutManager = new ViewPagerLayoutManager(this, LinearLayoutManager.VERTICAL);
        pagerLayoutManager.setOnViewPagerListener(this);
        videoAdapter = new VlogVideoAdapter(this, recycleView);

        recycleView.setLayoutManager(pagerLayoutManager);
        recycleView.setAdapter(videoAdapter);
        videoAdapter.setData(mDataList);
        recycleView.scrollToPosition(curPosition);

        mPresenter.getDetail(vlogId, userName);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void setListener() {
        recycleView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent e) {
                final int action = e.getActionMasked();
                switch (action) {
                    case MotionEvent.ACTION_DOWN://手指按下
                        break;
                    case MotionEvent.ACTION_CANCEL:
                        break;
                    case MotionEvent.ACTION_MOVE://手指移动（从手指按下到抬起 move多次执行）
                        break;
                    case MotionEvent.ACTION_UP://手指抬起
                        if (recycleView.getScrollState() == RecyclerView.SCROLL_STATE_DRAGGING &&
                                pagerLayoutManager.findSnapPosition() == 0) {
                            if (recycleView.getChildAt(0).getY() == 0 &&
                                    recycleView.canScrollVertically(1)) {//下滑操作
                                recycleView.stopScroll();
                            }
                        }
                        break;
                    default:
                        break;
                }

                return false;
            }
        });

        videoAdapter.setOnItemChildClickListener(new OnItemChildClickListener<SchoolVlogBean>() {
            @Override
            public void onClickListener(View view, final SchoolVlogBean bean, int position) {
                int id = view.getId();
                if (id == R.id.comment_num) {
                    SchoolVlogCommentPopupWindow popupWindow = new SchoolVlogCommentPopupWindow(SchoolVlogPlayActivity.this, vlogId);
                    popupWindow.showPopupWindow();
                } else if (id == R.id.follow_num) {
                    XXPermissions.with(SchoolVlogPlayActivity.this)
                            .permission(Permission.WRITE_EXTERNAL_STORAGE)
                            .request(new OnPermissionCallback() {
                                @Override
                                public void onGranted(List<String> permissions, boolean all) {
                                    if (all) {
                                        MShareBoard shareBoard = new MShareBoard(SchoolVlogPlayActivity.this, bean.getId() + "", bean.getInfo(), bean.getLogo(), "", 31, false);
                                        shareBoard.showPopupWindow();

                                        mPresenter.doShare(vlogId);
                                    }
                                }
                            });
                }
            }

            @Override
            public void onClickListener(View view, SchoolVlogBean bean, int position, boolean isFollow) {
                CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                    @Override
                    public void login(boolean isLogin) {
                        if (isLogin) {
                            userName = CommonUtils.getInstance().getUserName();
                            if (isFollow) {
                                mPresenter.cancelPraise(vlogId, userName);
                            } else {
                                mPresenter.doPraise(vlogId, userName);
                            }

                        } else {
                            Toasty.normal(SchoolVlogPlayActivity.this, "尚未登录或登录已失效！").show();
                            RouterManager.routerLogin(SchoolVlogPlayActivity.this, 0);
                        }
                    }

                    @Override
                    public void error(String s) {

                    }
                });
            }
        });

        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getData(tagId, lastId, lastBoost);
            }
        });
    }


    @OnClick(R2.id.close_btn)
    public void onClick() {
        finish();
    }

    @Override
    public void onInitComplete() {
        playVideo(curPosition);
    }

    @Override
    public void onPageSelected(int position, boolean isBottom) {
        if (viewHolder != null && viewHolder.videoTag != null) {
            viewHolder.videoTag.setVisibility(View.GONE);
        }

        if (isFirst) {
            curPosition = position;
            vlogId = mDataList.get(position).getId();
            mPresenter.getDetail(vlogId, userName);
        } else {
            if (position != curPosition) {
                curPosition = position;
                vlogId = mDataList.get(position).getId();
                mPresenter.getDetail(vlogId, userName);
            }
        }
    }

    @Override
    public void onPageRelease(boolean isNext, int position) {
        releaseVideo(position);
    }

    private void playVideo(final int position) {
        viewHolder = (VlogVideoAdapter.VideoViewHolder) recycleView.findViewHolderForLayoutPosition(position);
        SchoolVlogBean videoBean = videoAdapter.getDataByPosition(position);
        if (viewHolder != null && !viewHolder.videoView.isPlaying()) {
            viewHolder.videoView.setVideoPath(videoBean.getVideoUrl());
            viewHolder.videoView.getMediaPlayer().setOnInfoListener(new IMediaPlayer.OnInfoListener() {
                @Override
                public boolean onInfo(IMediaPlayer iMediaPlayer, int what, int extra) {
                    if (what == IMediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) {
                        viewHolder.sdvCover.setVisibility(View.INVISIBLE);
                    } else if (what == IMediaPlayer.MEDIA_INFO_VIDEO_ROTATION_CHANGED) {
                        //这里返回了视频旋转的角度，根据角度旋转视频到正确的画面
                        viewHolder.videoView.setRotation(extra);
                    }
                    return false;
                }
            });

            viewHolder.videoView.getMediaPlayer().setOnErrorListener(new IMediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(IMediaPlayer iMediaPlayer, int i, int i1) {
                    showToast("视频出错，加载失败！");
                    return false;
                }
            });

            viewHolder.videoView.setOnVideoProgressUpdateListener(new ListVideoView.OnVideoProgressListener() {
                @Override
                public void onProgress(float progress, long currentTime) {
                    viewHolder.progressBar.setProgress((int) (progress * 100));

                }
            });
            viewHolder.videoView.setLooping(true);
            viewHolder.videoView.prepareAsync();
        }
    }

    private void releaseVideo(int position) {
        VideoManager.releaseAll();
    }

    @Override
    protected void onPause() {
        super.onPause();
        VideoManager.pause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        VideoManager.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        VideoManager.releaseAll();
    }

    @Override
    public void setDetail(SchoolVlogBean bean) {
        isFirst = false;
        List<SchoolVlogBean> indexList = new ArrayList<>();
        indexList.addAll(mDataList);
        indexList.set(curPosition, bean);
        mDataList.clear();
        mDataList.addAll(indexList);
        videoAdapter.setData(mDataList);
        playVideo(curPosition);
    }

    @Override
    public void setError(String msg) {
        isFirst = false;
        showToast(msg);
        playVideo(curPosition);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void setPraiseSuccess(boolean isAdd, String msg) {
        if (viewHolder != null) {
            if (isAdd) {
                viewHolder.likeNum.setCompoundDrawablesWithIntrinsicBounds(null, ContextCompat.getDrawable(this, R.drawable.short_video_play_like_on_icon), null, null);
                mDataList.get(curPosition).setLikeCount(mDataList.get(curPosition).getLikeCount() + 1);
                viewHolder.likeNum.setText(mDataList.get(curPosition).getLikeCount() + "");
            } else {
                viewHolder.likeNum.setCompoundDrawablesWithIntrinsicBounds(null, ContextCompat.getDrawable(this, R.drawable.short_video_play_like_off_icon), null, null);
                mDataList.get(curPosition).setLikeCount(mDataList.get(curPosition).getLikeCount() - 1);
                viewHolder.likeNum.setText(mDataList.get(curPosition).getLikeCount() + "");
            }

        }
    }

    @Override
    public void setPraiseError(String msg) {
        showToast(msg);
    }

    @Override
    public void setData(List<SchoolVlogBean> beanList) {
        refresh.finishLoadMore();
        lastId = beanList.get(beanList.size() - 1).getId();
        lastBoost = beanList.get(beanList.size() - 1).getBoost();
        mDataList.addAll(beanList);
        videoAdapter.setData(mDataList);
    }

    @Override
    public void setDataError(String msg) {
        refresh.finishLoadMore();
        showToast(msg);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void shareSuccess() {
        mDataList.get(curPosition).setShareCount(mDataList.get(curPosition).getShareCount() + 1);
        viewHolder.followNum.setText(mDataList.get(curPosition).getShareCount() + "");
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);

    }
}
